﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using Fodee.BusinessComponent;
using Fodee.DataEntity;
using Fodee.Common;

namespace FodeeAdmin.SystemSettings
{
    public partial class UserGroupForm : BaseSystemSettingsForm
    {
        public UserGroupForm()
        {
            InitializeComponent();
            this.grid.AutoGenerateColumns = false;
            BindRoleCategory();
        }

        private fodUserGroupBC bc = new fodUserGroupBC();
        private fodRolesCategoryBC roleCategoryBC = new fodRolesCategoryBC();
        private fodRolesBC rolesBC = new fodRolesBC();

        public void InitForm()
        {
        }

        public void BindData()
        {
            FodeeDS = bc.GetAll();
            this.grid.DataSource = FodeeDS.fod_UserGroup.DefaultView;
            this.grid.ClearSelection();
            ClearForm();
        }

        public void BindRoleCategory()
        {
            FodeeDataSet dsRoleCategory = roleCategoryBC.GetAll();
            //this.checkedListBox1.DataSource = dsRoleCategory.fod_RolesCategory.DefaultView;
            //this.checkedListBox1.DisplayMember = "RoleCategoryName";
            //this.checkedListBox1.ValueMember = "ID";
            FodeeDataSet dsRoles = rolesBC.GetAll();

            if (dsRoleCategory == null)
            {
                return;
            }

            if (dsRoleCategory.fod_RolesCategory.Rows.Count == 0)
            {
                return;
            }

            foreach (FodeeDataSet.fod_RolesCategoryRow row in dsRoleCategory.fod_RolesCategory.Rows)
            {
                TreeNode tn = new TreeNode();
                tn.Text = row.RoleCategoryName;
                tn.Name = row.ID.ToString();
                this.treeView1.Nodes.Add(tn);

                if (dsRoles == null)
                {
                    continue;
                }

                if (dsRoles.fod_Roles.Count == 0)
                {
                    continue;
                }

                //var listRoles = (from r in dsRoles.fod_Roles.AsEnumerable()
                //         where r.RoleCategoryID == row.ID
                //         select r).ToList();

                DataRow[] listRoles = dsRoles.fod_Roles.Select(string.Format("RoleCategoryID={0}", row.ID));

                if (listRoles.Length == 0)
                {
                    continue;
                }

                foreach (FodeeDataSet.fod_RolesRow roleRow in listRoles)
                {
                    TreeNode tnChild = new TreeNode();
                    tnChild.Text = roleRow.RoleName;
                    tnChild.Name = roleRow.ID.ToString();
                    tn.Nodes.Add(tnChild);
                }
            }

            this.treeView1.ExpandAll();
        }

        public override void ClearForm()
        {
            base.ClearForm();
            this.grid.ClearSelection();
            ClearTree();
            SetOperation(Operation.Add);
        }

        private void ClearTree()
        {
            foreach (TreeNode tn in this.treeView1.Nodes)
            {
                tn.Checked = false;
                if (tn.Nodes.Count > 0)
                {
                    foreach (TreeNode n in tn.Nodes)
                    {
                        n.Checked = false;
                    }
                }
            }
        }

        public void AddData()
        {
            FodeeDataSet ds = new FodeeDataSet();
            FodeeDataSet.fod_UserGroupRow row = ds.fod_UserGroup.Newfod_UserGroupRow();
            row.UserGroupName = this.tbxUserGroupName.Text;
            //row.UserGroupRemarks = this.tbxUserGroupRemarks.Text;
            row.UserGroupRoles = GetUserGroupRoles();
            Util.SetCommonFields(row);
            ds.fod_UserGroup.Addfod_UserGroupRow(row);
            bool result = bc.Insert(ds);
            if (result)
            {
                MessageBox.Show("添加成功");
                BindData();
            }
            else
            {
                MessageBox.Show("添加失败");
            }
        }

        private string GetUserGroupRoles()
        {
            string result = string.Empty;

            foreach (TreeNode tn in this.treeView1.Nodes)
            {
                //if (tn.Checked)
                //{
                //    result += tn.Name+"|";
                //}
                if (tn.Nodes.Count > 0)
                {
                    foreach (TreeNode n in tn.Nodes)
                    {
                        if (n.Checked)
                        {
                            result += n.Name + "|";
                        }
                    }
                }
            }

            return result;
        }

        private void SetUserGroupRoles(string roles)
        {
            if(string.IsNullOrEmpty(roles))
            {
                return;
            }

            foreach (TreeNode tn in this.treeView1.Nodes)
            {
                bool isAllChecked = true;

                if (tn.Nodes.Count > 0)
                {
                    foreach (TreeNode n in tn.Nodes)
                    {
                        if (roles.Contains(n.Name))
                        {
                            n.Checked = true;
                        }
                        else
                        {
                            n.Checked = false;
                            isAllChecked = false;
                        }
                    }
                }
                else
                {
                    isAllChecked = false;
                }

                tn.Checked = isAllChecked;
            }
        }

        public void UpdateData()
        {
            FodeeDataSet.fod_UserGroupRow row = FodeeDS.fod_UserGroup.FindByID(KeyID);
            row.UserGroupName = this.tbxUserGroupName.Text;
            //row.UserGroupRemarks = this.tbxUserGroupRemarks.Text;
            row.UserGroupRoles = GetUserGroupRoles();
            bool result = bc.Update(FodeeDS);
            if (result)
            {
                MessageBox.Show("修改成功");
                BindData();
            }
            else
            {
                MessageBox.Show("修改失败");
            }
        }

        public void FillData()
        {
            FodeeDataSet.fod_UserGroupRow row = FodeeDS.fod_UserGroup.FindByID(KeyID);
            this.tbxUserGroupName.Text = row.UserGroupName;
            //this.tbxUserGroupRemarks.Text = row.UserGroupRemarks;
            if (!row.IsUserGroupRolesNull())
            {
                SetUserGroupRoles(row.UserGroupRoles);
            }
            else
            {
                ClearTree();
            }

            SetOperation(Operation.Edit);

            if (!base.ValidateForm())
            {
                return;
            }
        }

        public void DeleteData()
        {
            bool result = bc.Delete(KeyID);
            if (result)
            {
                MessageBox.Show("删除成功");
                BindData();
            }
            else
            {
                MessageBox.Show("删除失败");
            }
        }

        public void SetOperation(Operation operation)
        {
            if (operation == Operation.Add)
            {
                this.btnSave.Text = "添加";
            }
            else
            {
                this.btnSave.Text = "修改";
            }

            FormOperation = operation;
        }

        private void UserGroupForm_Load(object sender, EventArgs e)
        {
            BindData();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!base.ValidateForm())
            {
                return;
            }

            if (FormOperation == Operation.Edit)
            {
                UpdateData();
            }
            else
            {
                AddData();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void grid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }

            KeyID = int.Parse(this.grid.Rows[e.RowIndex].Cells["ID"].Value.ToString());
            string action = this.grid.Columns[e.ColumnIndex].Name;
            if (action.ToLower() == "delete")
            {
                bool isDelete = MessageBox.Show("确定删除吗?", "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK;
                if (isDelete)
                {
                    DeleteData();
                }
            }
            else
            {
                FillData();
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Nodes.Count > 0)
            {
                foreach (TreeNode n in e.Node.Nodes)
                {
                    n.Checked = e.Node.Checked;
                }
            }

            if (e.Node.Parent != null)
            {
                if (!e.Node.Checked)
                {
                    e.Node.Parent.Checked = false;
                }
                else
                {
                    bool isAllChecked = true;
                    foreach (TreeNode n in e.Node.Parent.Nodes)
                    {
                        if (!n.Checked)
                        {
                            isAllChecked = false;
                            break;
                        }
                    }

                    e.Node.Parent.Checked = isAllChecked;
                }
            }
        }

    }
}
